public class Sort {
    //也可以对链表起作用，同样是O(nlogn)
    public static void sort(int[] nums) {
        for (int size = 1; size <= nums.length; size += size) {
            for (int i = 0; i + size < nums.length; i += size + size) {
                merge(nums, i, i + size - 1, Math.min(i + size - 1 + size, nums.length - 1));
            }
        }
    }

    public static void merge(int[] nums, int lo, int mid, int hi) {
        int[] temp = new int[hi - lo + 1];
        for (int i = lo; i <= hi; i++) {
            temp[i - lo] = nums[i];
        }
        int index = lo;
        int i = 0, j = mid + 1 - lo;
        while (i <= mid - lo || j <= hi - lo) {
            if (i > mid - lo) {
                nums[index++] = temp[j++];
            } else if (j > hi - lo) {
                nums[index++] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                nums[index++] = temp[i++];
            } else {
                nums[index++] = temp[j++];
            }
        }
     }

    public static void main(String[] args) {
        int[] nums = {4, 3, 0, 8, 1, 7};
        sort(nums);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }

}
